package data_treating

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/xormplus/xorm"
	"goocr/config"
	"goocr/util"
	"os"
	"os/exec"
)

func init() {
	//连接数据库
	if err := InitDB(); err != nil {
		util.LogError(fmt.Sprintf("初始化数据库出错:%v", err))
		if err = startDbServer(); err != nil {
			util.LogError(fmt.Sprintf("启动MySQL服务出错:%v", err))
			os.Exit(-1)
		}
		util.LogInfo("启动MySQL服务完成")
	}
	util.LogInfo("初始化数据库完成")
}

// DB 定义一个全局对象db
var DB *xorm.Engine

func InitDB() (err error) {
	mysqlInfo := config.Conf.MysqlInfo
	conn := fmt.Sprintf("tcp(%s:%d)/%s?charset=utf8", mysqlInfo.Host, mysqlInfo.Post, mysqlInfo.DbName)
	dsn := fmt.Sprintf("%s:%s@%s", mysqlInfo.UserName, mysqlInfo.Password, conn)
	DB, err = xorm.NewEngine("mysql", dsn)
	if err != nil {
		return
	}
	err = DB.Ping()
	return
}

// 启动MySQL服务
func startDbServer() error {
	cmd := exec.Command("net", "start", "mysql")
	return cmd.Run()
}
